package com.lab.webSocket.service.impl;

import com.lab.webSocket.dto.ChatLogDto;
import com.lab.webSocket.model.ChatLogEntity;
import com.lab.webSocket.repository.ChatLogRepository;
import com.lab.webSocket.repository.UserRepository;
import com.lab.webSocket.service.ChatService;
import com.lab.webSocket.webSocket.dto.TextChatResultDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by xu_jiaHui on 2017/8/31.
 */
@Service
public class ChatServiceImpl implements ChatService {
    @Resource
    private ChatLogRepository chatLogRepository;

    @Resource
    private UserRepository userRepository;

    public Integer sendMessage(TextChatResultDto chatResultDto) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String sendTime = df.format(new Date());// new Date()为获取当前系统时间
        ChatLogEntity chatLogEntity = new ChatLogEntity(chatResultDto.getContent(),
                chatResultDto.getType(), chatResultDto.getUserAccount(), sendTime, chatResultDto.getUserTarget());
        return chatLogRepository.save(chatLogEntity).getChatLogId();
    }

    @Transactional
    public Integer updateLogoutTime(String userAccount) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String logoutTime = df.format(new Date());// new Date()为获取当前系统时间
        System.out.println("退出时间为:" + logoutTime);
        return userRepository.updateLogoutTime(userAccount, logoutTime);

    }

    @Transactional
    public List<ChatLogDto> getLastChatLog(String userAccount) throws Exception {
        List<ChatLogDto> chatLogDtos = chatLogRepository.getLastChatLog(userAccount);
        return chatLogDtos;
    }

    @Transactional
    public Integer deleteChatLog(String chatLogIds) throws Exception {
        String[] chatLogIdList = chatLogIds.split(",");
        for (String chatLogId : chatLogIdList) {
            if (!chatLogId.equals(""))
                chatLogRepository.deleteChatLog(Integer.parseInt(chatLogId));
        }
        return chatLogIdList.length;
    }

}
